package com.tanhua.server.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.domain.mysql.Answer;
import com.tanhua.model.domain.mysql.QuestionList;
import com.tanhua.model.dto.AnswerDto;
import com.tanhua.server.service.TestSoulService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lxb哦吼吼
 * @version 1.0
 * @description: TODO
 * @date 2021/11/20 21:23
 */

@RestController
@RequestMapping("/testSoul")
public class TestSoulController {

    @Autowired
    private TestSoulService testSoulService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取测试题
     *
     * @return
     */
    @GetMapping
    public ResponseEntity getSoulList() {
        String json = (String) redisTemplate.opsForValue().get(Constants.TEST_SOUL);
        List<QuestionList> questionList;
        if (!BeanUtil.isEmpty(json)) {
            questionList = JSON.parseObject(json, List.class);
        } else {
            questionList = testSoulService.getSoulList();
        }
        return ResponseEntity.ok(questionList);
    }

    /**
     * 提交测试答案
     *
     * @return
     */

    @PostMapping
    public ResponseEntity answer(@RequestBody Map<String, List<AnswerDto>> map) {
        List<AnswerDto> answerDtoList = map.get("answers");
        String questionId = answerDtoList.get(0).getQuestionId();
        List<String> optionIdList = new ArrayList<>();
        for (AnswerDto answerDto : answerDtoList) {
            optionIdList.add(answerDto.getOptionId());
        }
        String reportId = testSoulService.getReportId(questionId, optionIdList);
        return ResponseEntity.ok(reportId);
    }

    /**
     * 测试查看结果
     *
     * @param id
     * @return
     */
    @GetMapping("/report/{id}")
    public ResponseEntity getReport(@PathVariable String id) {
        Answer answer = testSoulService.getReport(id);
        return ResponseEntity.ok(answer);
    }
}
